#!/bin/bash

# MarkEdit 部署脚本

set -e

# 配置
SERVICE_NAME="markedit"
DEPLOY_DIR="/opt/markedit"
SYSTEMD_SERVICE="/etc/systemd/system/markedit.service"
USER="markedit"
GROUP="markedit"

echo "开始部署 MarkEdit..."

# 检查是否为root用户
if [ "$EUID" -ne 0 ]; then
    echo "请使用root权限运行此脚本"
    exit 1
fi

# 创建用户和组
if ! id "$USER" &>/dev/null; then
    echo "创建用户: $USER"
    useradd -r -s /bin/false -d $DEPLOY_DIR $USER
fi

# 创建部署目录
echo "创建部署目录: $DEPLOY_DIR"
mkdir -p $DEPLOY_DIR
mkdir -p $DEPLOY_DIR/logs
mkdir -p $DEPLOY_DIR/uploads
mkdir -p $DEPLOY_DIR/temp

# 停止现有服务
if systemctl is-active --quiet $SERVICE_NAME; then
    echo "停止现有服务..."
    systemctl stop $SERVICE_NAME
fi

# 复制文件
echo "复制应用文件..."
if [ -f "build/markedit" ]; then
    cp build/markedit $DEPLOY_DIR/
    chmod +x $DEPLOY_DIR/markedit
else
    echo "错误: 未找到构建文件 build/markedit"
    echo "请先运行构建脚本: ./scripts/build.sh"
    exit 1
fi

if [ -d "build/config" ]; then
    cp -r build/config $DEPLOY_DIR/
fi

if [ -d "build/web" ]; then
    cp -r build/web $DEPLOY_DIR/
fi

# 设置权限
chown -R $USER:$GROUP $DEPLOY_DIR
chmod -R 755 $DEPLOY_DIR

# 创建systemd服务文件
echo "创建systemd服务..."
cat > $SYSTEMD_SERVICE << EOF
[Unit]
Description=MarkEdit Markdown Editor
After=network.target

[Service]
Type=simple
User=$USER
Group=$GROUP
WorkingDirectory=$DEPLOY_DIR
ExecStart=$DEPLOY_DIR/markedit
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal
SyslogIdentifier=markedit

# 环境变量
Environment=GIN_MODE=release
Environment=TZ=Asia/Shanghai

# 安全设置
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=$DEPLOY_DIR

[Install]
WantedBy=multi-user.target
EOF

# 重新加载systemd
systemctl daemon-reload

# 启用并启动服务
echo "启用并启动服务..."
systemctl enable $SERVICE_NAME
systemctl start $SERVICE_NAME

# 检查服务状态
sleep 2
if systemctl is-active --quiet $SERVICE_NAME; then
    echo "部署成功！"
    echo ""
    echo "服务状态:"
    systemctl status $SERVICE_NAME --no-pager
    echo ""
    echo "应用已启动在: http://localhost:8080"
    echo ""
    echo "常用命令:"
    echo "  查看状态: systemctl status $SERVICE_NAME"
    echo "  查看日志: journalctl -u $SERVICE_NAME -f"
    echo "  重启服务: systemctl restart $SERVICE_NAME"
    echo "  停止服务: systemctl stop $SERVICE_NAME"
else
    echo "部署失败！"
    echo "查看日志: journalctl -u $SERVICE_NAME -n 50"
    exit 1
fi